import os
import sys
import pickle


class DataHanler(object):
    '''
    数据存取
    '''
    @staticmethod
    def save(obj, path):
        with open(path, 'wb') as f:
            pickle.dump(obj, f)
        return True

    @staticmethod
    def load(path):
        with open(path, 'rb') as f:
            return pickle.load(f)


class School(DataHanler):
    '''
    定义学校
    '''

    def __init__(self, s_id, name, addr):
        self.s_id = s_id
        self.name = name
        self.addr = addr
        self.teachers = []
        self.students = []
        self.grades = []
        self.courses = []

    def hire(self, obj):
        self.teachers.append(obj)

    def register(self, obj):
        self.students.append(obj)

    def add_grade(self, obj):
        self.grades.append(obj)

    def add_course(self, obj):
        self.courses.append(obj)

    def info(self):
        print(' school %s information '.center(50, '-') % self.name)
        print('school No.: %s' % self.s_id)
        print('school name: %s' % self.name)
        print('school addr: %s' % self.addr)
        print('-'*50)
        print(' teacher information '.center(50, '-'))
        if self.teachers:
            for teacher in self.teachers:
                teacher.info()
        else:
            print('not found teacher information')

        print(' student information '.center(50, '-'))
        if self.students:
            for student in self.students:
                student.info()
        else:
            print('not found student information')

        print(' grade information '.center(50, '-'))
        if self.grades:
            for grade in self.grades:
                grade.info()
        else:
            print('not found grade information')

        print(' course information '.center(50, '-'))
        if self.courses:
            for course in self.courses:
                course.info()
        else:
            print('not found course information')

class Teacher(DataHanler):
    '''
    定义老师
    '''

    def __init__(self, t_id, name, age, salary, s_id, g_id, c_id):
        self.t_id = t_id
        self.name = name
        self.age = age
        self.salary = salary
        self.s_id = s_id
        self.g_id = g_id
        self.c_id = c_id

    def info(self):
        print(' teacher %s infomation '.center(50, '-') % self.name)
        print('teacher No.: %s' % self.t_id)
        print('teacher name: %s' % self.name)
        print('teacher age: %s' % self.age)
        print('teacher salary: %s' % self.salary)


class Student(DataHanler):
    '''
    定义学员
    '''

    def __init__(self, stu_id, name, age, s_id, g_id, c_id, t_id):
        self.stu_id = stu_id
        self.name = name
        self.age = age
        self.s_id = s_id
        self.g_id = g_id
        self.c_id = c_id
        self.t_id = t_id

    def info(self):
        print(' student %s infomation '.center(50, '-') % self.name)
        print('sdudent No.: %s' % self.stu_id)
        print('sdudent name: %s' % self.name)
        print('sdudent age: %s' % self.age)


class Grade(DataHanler):
    '''
    定义班级
    '''

    def __init__(self, g_id, name, s_id):
        self.g_id = g_id
        self.name = name
        self.s_id = s_id

    def info(self):
        print(' grade %s infomation '.center(50, '-') % self.name)
        print('grade No.: %s' % self.g_id)
        print('grade name: %s' % self.name)


class Course(DataHanler):
    '''
    定义课程
    '''

    def __init__(self, c_id, name, term, price, s_id, g_id,):
        self.c_id = c_id
        self.name = name
        self.term = term
        self.price = price
        self.s_id = s_id
        self.g_id = g_id

    def info(self):
        print(' course %s infomation '.center(50, '-') % self.name)
        print('course No.: %s' % self.c_id)
        print('course name: %s' % self.name)
        print('course term: %s' % self.term)
        print('course price: %s' % self.price)


def student_view():
    '''
    学生入口
    '''
    print('this is student view')


def teacher_view():
    '''
    教师入口
    '''
    print('this is teacher view')


def admin_view():
    '''
    管理入口
    '''
    schools = [{'s_id': 0, 'name': 'txketang', 'addr': 'beijing'},
               {'s_id': 1, 'name': '163ketang', 'addr': 'shanghai'}]
    while True:
        for item in schools:
            print('[%s] %s' % (item['s_id'], item['name']))
        print('[b] go back')
        print('[q] exit')
        choice = get_choice()
        if choice.isdigit():
            print('loading school data ...')
            choice = int(choice)
            db_name = schools[choice]['name']
            if os.path.isfile(db_name):
                school = School.load(db_name)
            else:
                school = schools[choice]
                school = School(school['s_id'], school['name'], school['addr'])
                if not school.save(school, school.name):
                    school = ''
            if school:
                print('OK: load %s school data success' % school.name)
                while True:
                    print('-'*50)
                    print('[0] school information')
                    print('[1] hire a new teacher')
                    print('[2] add a new grade')
                    print('[3] add a new course')
                    print('[b] go back')
                    print('[q] exit')
                    choice = get_choice()
                    if choice == 'b':
                        break
                    elif choice == 'q':
                        print('exit ...')
                        exit()
                    elif choice.isdigit():
                        if choice == '0':
                            school.info()
                        elif choice == '1':
                            print('will hire a new teacher')
                            t_name = input('teacher name: ')
                            t_age = input('teacher age: ')
                            t_salary = input('teacher salary: ')
                            s_id = school.s_id
                            g_id_list = []
                            if school.grades:
                                for grade in school.grades:
                                    print('[%s] %s' % (grade.g_id, grade.name))
                                    g_id_list.append(grade.g_id)
                                print('choice a grade')
                                g_id = get_choice()
                                if g_id.isdigit() and int(g_id) in g_id_list:
                                    g_id = int(g_id)
                                else:
                                    g_id = ''
                                    print('Error: chose a invalid grade id')
                                    continue
                            else:
                                print('Error: not found grade')
                                continue
                            if school.courses:
                                c_id_list = []
                                for course in school.courses:
                                    print('[%s] %s' % (course.c_id, course.name))
                                    c_id_list.append(course.c_id)
                                print('choice a course')
                                c_id = get_choice()
                                if c_id.isdigit() and int(c_id) in c_id_list:
                                    c_id = int(c_id)
                                else:
                                    c_id = ''
                                    print('Error: chose a invalid course id')
                                    continue
                            else:
                                print('Error: not found course')
                                continue
                            if school.teachers:
                                t_id = int(school.teachers[-1].t_id) + 1
                            else:
                                t_id = 0
                            teacher_obj = Teacher(t_id, t_name, t_age, t_salary, s_id, g_id, c_id)
                            school.hire(teacher_obj)
                            if school.save(school, school.name):
                                print('Ok: hire a new teacher %s success' % t_name)
                            else:
                                print('Error: hire a new teacher failed')
                                continue
                        elif choice == '2':
                            print('will add a new grade')
                            g_name = input('grade name: ')
                            s_id = school.s_id
                            if school.grades:
                                g_id = int(school.grades[-1].g_id) + 1
                            else:
                                g_id = 0
                            grade_obj = Grade(g_id, g_name, s_id)
                            school.add_grade(grade_obj)
                            if school.save(school, school.name):
                                print('OK: add a new grade %s success' % g_name)
                            else:
                                print('Error: add a new grade failed')
                                continue
                        elif choice == '3':
                            print('will add a new course')
                            c_name = input('course name: ')
                            c_term = input('course term: ')
                            c_price = input('course price: ')
                            if school.courses:
                                c_id = int(school.courses[-1].c_id) + 1
                            else:
                                c_id = 0
                            s_id = school.s_id
                            if school.grades:
                                g_id_list = []
                                for grade in school.grades:
                                    print('[%s] %s' % (grade.g_id, grade.name))
                                    g_id_list.append(grade.g_id)
                                print('choice a grade id')
                                g_id = get_choice()
                                if g_id.isdigit() and int(g_id) in g_id_list:
                                    g_id = int(g_id)
                                else:
                                    print('Error: invalid choice')
                                    continue
                            else:
                                print('Error: not found grade')
                                continue
                            course_obj = Course(c_id, c_name, c_term, c_price, s_id, g_id)
                            school.add_course(course_obj)
                            if school.save(school, school.name):
                                print('OK: add a new course %s success' % c_name)
                            else:
                                print('Error: add a new course failed')
                                continue
                    else:
                        print('Error: invalid input')

            else:
                print('Error: load %s school data failed' % school.name)
        elif choice == 'b':
            break
        else:
            print('Error: invalid choice')

def get_choice():
    choice = input('enter your choice: ')
    if choice == 'q':
        print('exit ...')
        exit()
    else:
        return choice


def main():
    '''
    系统入口
    '''

    while True:
        print(' menu '.center(50, '='))
        print('[0] admin view')
        print('[1] teacher view')
        print('[2] student view')
        print('[q] exit')
        choice = get_choice()
        if choice.isdigit():
            if choice == '0':
                admin_view()
            elif choice == '1':
                teacher_view()
            elif choice == '2':
                student_view()
            else:
                print('Error: invalid choice')
        else:
            print('Error: invalid choice')


if __name__ == '__main__':
    main()
